import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/CentrePage/Energy/EnergyViewDetail.dart';
import 'package:flutter_wisave/widgets/indicator.dart';
import 'package:flutter_wisave/widgets/LineChartSamplep.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/Common/TimeSwitching.dart';
import 'package:flutter_wisave/CentrePage/Class/SteelOutDay.dart';
import 'package:flutter_wisave/CentrePage/Class/PredictionClass.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../../widgets/AppColors.dart';
import '../../CentrePage/Production/ProductionDetailPage.dart';

class ProductionPage extends StatefulWidget {
  final int initialIndex;

  const ProductionPage({
    super.key,
    this.initialIndex = 0,
  });

  @override
  State<ProductionPage> createState() => _ProductionPageState();
}

class _ProductionPageState extends State<ProductionPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final NetworkService _networkService = NetworkService();
  DateTime _currentDayDateTime = DateTime.now();
  DateTime _currentMonthDateTime = DateTime.now();
  late String currentDayDate;
  late String currentMonthDate;
  Map<String, dynamic> _steelOutDay = {};
  SteelOutDay? _steelOutM;
  List<dynamic> _prediction = [];
  // Map<String, dynamic> _outList = {};
  PredictionClass? _outList;
  late String startDate;
  late String endDate;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: widget.initialIndex,
    );
    _networkService.setupInterceptors(context);
    currentDayDate = _formatDate(_currentDayDateTime);
    currentMonthDate = _formatMonthDate(_currentMonthDateTime);
    _loadData();
    _loadDataM();
    _loadDataRatio();
    _loadDataSteeloutmonth();
  }

  ///日
  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result['code'] == 200 && result['data'] != null) {
        setState(() {
          _steelOutDay = result['data'] as Map<String, dynamic>;
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      // final response = await _networkService.get(
      //     '/plcTimer/steeloutday/steelOutDay?companyId=$deptID&date=$currentDayDate');
      final response = await _networkService.get(
          '/plcTimer/steelouthour/dayInfo?companyId=$deptID&date=$currentDayDate');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  void _onDayDateChanged(DateTime newDate) {
    setState(() {
      _currentDayDateTime = newDate;
      currentDayDate = _formatDate(_currentDayDateTime);
      _loadData();
    });
  }

  //月
  Future<void> _loadDataM() async {
    try {
      final result = await _fetchDataM();
      print('API Response: $result'); // 打印整个响应以便调试

      if (result is Map<String, dynamic>) {
        if (result['code'] == 200) {
          var data = result['rows'] ?? result['data'];
          if (data != null) {
            print('Data to be parsed: $data'); // 打印将要解析的数据
            try {
              setState(() {
                _steelOutM =
                    SteelOutDay.fromJson(data is List ? data[0] : data);
                print('Parsed SteelOutDay: $_steelOutM');
              });
            } catch (parseError) {
              print('Error parsing SteelOutDay: $parseError');
              // 这里可以添加更详细的错误处理逻辑
            }
          } else {
            print('Error: No data found in the response');
          }
        } else {
          print('Error: ${result['msg']}');
        }
      } else {
        print('Error: Unexpected response format');
      }
    } catch (e) {
      print('Error in _loadDataM: $e');
    }
  }

  //折线图数据
  Future<dynamic> _fetchDataM() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/steeloutday/steelOutDay?companyId=$deptID&date=$currentMonthDate');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchDataM: $e');
      rethrow;
    }
  }

  String _formatMonthDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}';
  }

  void _onMonthDateChanged(DateTime newDate) {
    setState(() {
      _currentMonthDateTime = newDate;
      currentMonthDate = _formatMonthDate(_currentMonthDateTime);
      startDate =
          DateTime(_currentMonthDateTime.year, _currentMonthDateTime.month, 1)
              .toString()
              .split(' ')[0];
      endDate = DateTime(
              _currentMonthDateTime.year, _currentMonthDateTime.month + 1, 0)
          .toString()
          .split(' ')[0];
      _loadDataM(); // Call this to load data for the new month
      _loadDataRatio();
    });
  }

  //各班组产能预测
  Future<void> _loadDataRatio() async {
    try {
      final result = await _fetchDataRatio();
      if (result['code'] == 200) {
        setState(() {
          _prediction = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
          // PredictionClass.fromJson(result['data']);
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<dynamic> _fetchDataRatio() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/teampdicount/steelOutRatio?companyId=$deptID&date=$currentMonthDate');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchDataM: $e');
      rethrow;
    }
  }

  //产能预测
  Future<void> _loadDataSteeloutmonth() async {
    try {
      final result = await _fetchDataSteeloutmonth();
      if (result['code'] == 200) {
        print('产能预测数据: ${result}');
        setState(() {
          // _outList = result['data'] as Map<String, dynamic>;
          _outList = PredictionClass.fromJson(result['data']);
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<dynamic> _fetchDataSteeloutmonth() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/steeloutmonth/steelOutMonthRatio?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('_fetchDataSteeloutmonth Failed to load data');
      }
    } catch (e) {
      print('_fetchDataSteeloutmonth Error in: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    // 获取屏幕的宽度和高度
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('生产管理'),
        foregroundColor: AppColors.textPrimary,
        centerTitle: true,
        backgroundColor: Colors.transparent, // Make AppBar transparent
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(48), // Adjust height as needed
          child: Container(
            decoration: const BoxDecoration(
              color: Colors.transparent, // Set the background color
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
            child: TabBar(
              isScrollable: false,
              indicatorColor: Colors.blue,
              indicatorWeight: 2,
              indicatorPadding: const EdgeInsets.only(right: 50, left: 50),
              indicatorSize: TabBarIndicatorSize.tab,
              labelColor: TDTheme.of(context).grayColor12,
              unselectedLabelColor: TDTheme.of(context).grayColor8,
              labelStyle:
                  const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              unselectedLabelStyle: const TextStyle(fontSize: 16),
              controller: _tabController,
              tabs: [
                Tab(
                    child: Text("实际产量",
                        style: TextStyle(color: AppColors.textPrimary))),
                Tab(
                    child: Text("产能预测",
                        style: TextStyle(color: AppColors.textPrimary))),
              ],
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          ListView(
            children: [
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Container(
                  padding: EdgeInsets.all(16.0),
                  decoration: BoxDecoration(
                    color: AppColors.cardColor,
                    borderRadius: BorderRadius.circular(8.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        blurRadius: 6.0,
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      TimeSwitching(
                        mode: SwitchingMode.day,
                        onDateChanged: _onDayDateChanged,
                      ),
                      Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ..._dayInfoView(_steelOutDay['steelOut'] ?? 0,
                                _steelOutDay['rate'] ?? 0, screenWidth),
                            // ..._buttonWithType(
                            //     0,
                            //     _steelOutDay?.steelOut?.toString() ?? '-',
                            //     screenWidth),
                            // ..._buttonWithType(
                            //     1,
                            //     _steelOutDay?.rate?.toString() ?? '-',
                            //     screenWidth),
                          ]),
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Container(
                  padding: EdgeInsets.all(16.0),
                  decoration: BoxDecoration(
                    color: AppColors.cardColor,
                    borderRadius: BorderRadius.circular(8.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        blurRadius: 6.0,
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      TimeSwitching(
                        mode: SwitchingMode.month,
                        onDateChanged: _onMonthDateChanged,
                      ),
                      SizedBox(height: 6.0),
                      Container(
                        width: screenWidth - 80, // 设置宽度
                        child: Text(
                          '产量趋势（吨）',
                          textAlign: TextAlign.left,
                          style: TextStyle(
                            color: AppColors.textPrimary,
                            fontSize: 14,
                          ),
                        ),
                      ),
                      SizedBox(height: 6.0),
                      Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              height: 184, // 调整背景图的高度
                              width: screenWidth - 80,
                              decoration: BoxDecoration(
                                // image: const DecorationImage(
                                //   image: AssetImage(
                                //       'assets/images/centre/production_bg3.png'),
                                //   fit: BoxFit.cover,
                                // ),
                                borderRadius: BorderRadius.circular(8.0),
                              ),

                              child: Stack(
                                children: [
                                  Positioned(
                                    // bottom: 10,
                                    width: screenWidth - 80,
                                    child: const Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      mainAxisAlignment:
                                          MainAxisAlignment.center, // 垂直居中
                                      children: [
                                        LineChartSamplep(
                                          spots: [2, 4, 9, 3, 8, 2],
                                          xTitle: [
                                            '12:00',
                                            '12:20',
                                            '12:40',
                                            '1:00',
                                            '1:20',
                                            '1:40'
                                          ], // 传递 xTitle 数据
                                        ),

                                        // GestureDetector(
                                        //   onTap: () {
                                        //     Navigator.push(
                                        //       context,
                                        //       MaterialPageRoute(
                                        //           builder: (context) =>
                                        //               EnergyViewDetail()),
                                        //     );
                                        //   },
                                        //   child: Image.asset(
                                        //     'assets/images/centre/top1.png',
                                        //   ),
                                        // ),
                                        // const Text(
                                        //   '月产量(吨)',
                                        //   textAlign: TextAlign.center,
                                        //   style: TextStyle(
                                        //     color: Colors.black,
                                        //     fontSize: 14,
                                        //   ),
                                        // ),
                                        // Text(
                                        //   _steelOutM?.steelOut?.toString() ??
                                        //       '-',
                                        //   textAlign: TextAlign.center,
                                        //   style: const TextStyle(
                                        //       color: Color(0xFFFCAA3F),
                                        //       fontSize: 30,
                                        //       fontWeight: FontWeight.bold),
                                        // ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ]),
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Container(
                  padding: EdgeInsets.all(16.0),
                  decoration: BoxDecoration(
                    color: AppColors.cardColor,
                    borderRadius: BorderRadius.circular(8.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        blurRadius: 6.0,
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '各班各组月产量对比',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: AppColors.textPrimary),
                          ),
                          const Expanded(child: SizedBox()),
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => ProductionDetailPage(),
                                ),
                              );
                            },
                            child: Text(
                              '历史查询 >',
                              style: TextStyle(
                                  fontSize: 12,
                                  fontWeight: FontWeight.normal,
                                  color: AppColors.textSecondary),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        width: double.infinity,
                        child: Center(
                          child: PieChartSample3(
                            prediction: _prediction,
                          ),
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          if (_prediction.length > 0)
                            Indicator(
                              color: Color(0xFF2AB6F7),
                              text: _prediction[0]['team'].toString(),
                              isSquare: true,
                            ),
                          SizedBox(width: 20),
                          if (_prediction.length > 1)
                            Indicator(
                              color: Color(0xFF814FF3),
                              text: _prediction[1]['team'].toString(),
                              isSquare: true,
                            ),
                          SizedBox(width: 20),
                          if (_prediction.length > 2)
                            Indicator(
                              color: Color(0xFF53E0B1),
                              text: _prediction[2]['team'].toString(),
                              isSquare: true,
                            ),
                          SizedBox(width: 20),
                          if (_prediction.length > 3)
                            Indicator(
                              color: Color(0xFFFCAA3F),
                              text: _prediction[3]['team'].toString(),
                              isSquare: true,
                            ),
                          SizedBox(width: 20),
                          if (_prediction.length > 4)
                            Indicator(
                              color: Color(0xFFFD5864),
                              text: _prediction[4]['team'].toString(),
                              isSquare: true,
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          ListView(
            children: [
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Container(
                    padding: EdgeInsets.all(16.0),
                    decoration: BoxDecoration(
                      color: AppColors.cardColor,
                      borderRadius: BorderRadius.circular(8.0),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.2),
                          blurRadius: 6.0,
                        ),
                      ],
                    ),
                    child: Stack(children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                height: 210.0,
                                child: PieChartSample2(
                                    initialv: ((_outList?.presentOut ?? 0) /
                                            (_outList?.predictionOut ?? 1) *
                                            100) ??
                                        0.0),
                              ),
                            ],
                          ),
                          const SizedBox(height: 10),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const SizedBox(height: 7, width: 7),
                              Indicator(
                                color: const Color(0xFF2AB6F7),
                                text: '',
                                isSquare: true,
                              ),
                              Text(
                                ' 实际产能/预测产能',
                                style: TextStyle(
                                    fontSize: 14, color: AppColors.textPrimary),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Positioned(
                        top: 30,
                        left: 0,
                        right: 0,
                        child: Center(
                          child: SizedBox(
                            height: 216,
                            width: 216,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                const SizedBox(height: 10),
                                Text(
                                  '${_formatMonthDate(DateTime.now())}',
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: AppColors.textPrimary,
                                  ),
                                ),
                                Text(_outList?.presentOut.toString() ?? "--",
                                    style: TextStyle(
                                      fontSize: 40,
                                      color: Color(0xFF2AB6F7),
                                    )),
                                Text(
                                    '${((_outList?.presentOut ?? 0) / (_outList?.predictionOut ?? 1) * 100).toInt()}%',
                                    style: TextStyle(
                                      fontSize: 22,
                                      color: Color(0xFFFCAA3F),
                                    )),
                                const SizedBox(height: 10),
                                Text(
                                  '(吨/月)',
                                  style: TextStyle(
                                      fontSize: 13,
                                      color: AppColors.textSecondary),
                                ),
                                Expanded(child: SizedBox()),
                              ],
                            ),
                          ),
                        ),
                      )
                    ])),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Container(
                  padding: EdgeInsets.all(16.0),
                  decoration: BoxDecoration(
                    color: AppColors.cardColor,
                    borderRadius: BorderRadius.circular(8.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        blurRadius: 6.0,
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        '设计最大产量：${_outList?.designMaxOut.toString() ?? '--'}（吨/月）',
                        style: TextStyle(
                            fontSize: 14, color: AppColors.textSecondary),
                      ),
                      SizedBox(height: 16.0),
                      Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ..._forecastWithType(
                                0, _outList?.yearRatio ?? 0, screenWidth),
                            ..._forecastWithType(
                                1, _outList?.monthRatio ?? 0, screenWidth),
                            ..._forecastWithType(
                                2, _outList?.maxRatio ?? 0, screenWidth),
                          ]),
                    ],
                  ),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

List<Widget> _dayInfoView(num steelOut, num rate, double screenWidth) {
  return [
    Container(
      width: screenWidth - 70,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            // Added Row to wrap the Column
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('出钢节奏（秒）',
                      style: TextStyle(color: AppColors.textPrimary)),
                  SizedBox(height: 4),
                  Text(
                    rate.toString(),
                    style: TextStyle(
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                        color: AppColors.textPrimary),
                  ),
                ],
              ),
              Text(
                steelOut.toString() + 't',
                style: const TextStyle(
                    fontSize: 23.0,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF2AB6F7)),
              ),
              SizedBox(
                width: 1,
              )
            ],
          ),
          Row(
            children: [
              Image.asset('assets/images/centre/Slice_1.png'),
              Image.asset('assets/images/centre/Slice_1_1.png'),
              for (int i = 0; i < (screenWidth - 70 - 204) / 30; i++)
                Image.asset('assets/images/centre/Slice_2.png'),
              Image.asset('assets/images/centre/Slice_3.png'),
              Image.asset('assets/images/centre/Slice_4.png'),
            ],
          )
        ],
      ),
    ),
  ];
}

List<Widget> _buttonWithType(num type, String content, double screenWidth) {
  return [
    Container(
      margin: EdgeInsets.only(left: type == 1 ? 18.0 : 0), // 设置间距
      height: 84, // 调整背景图的高度
      width: screenWidth / 2 - 50,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(
              'assets/images/centre/production_bg${type + 1}.png'), // 替换为你的图片路径
          fit: BoxFit.cover,
        ),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Stack(
        children: [
          Positioned(
            bottom: 10,
            width: screenWidth / 2 - 50,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  type == 0 ? '日产量(吨)' : '出钢节奏(秒)',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: AppColors.textPrimary,
                    fontSize: 14,
                  ),
                ),
                Text(
                  content,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: type == 0 ? Color(0xFF2AB6F7) : Color(0xFF814FF3),
                      fontSize: 30,
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
        ],
      ),
    ),
  ];
}

List<Widget> _forecastWithType(num type, double content, double screenWidth) {
  String title = '同比去年';
  if (type == 1) {
    title = '环比上月';
  } else if (type == 2) {
    title = '比历史最佳';
  }

  return [
    Container(
      margin: EdgeInsets.only(left: type == 0 ? 0 : 12),
      height: 84,
      width: screenWidth / 3 - 36,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(AppColors.isDarkMode
              ? 'assets/images/centre/production_bg6_b.png'
              : 'assets/images/centre/production_bg1.png'),
          fit: BoxFit.cover,
        ),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Stack(
        children: [
          Positioned(
            bottom: 10,
            width: screenWidth / 3 - 36,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center, // 垂直居中
              children: [
                Text(
                  title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: AppColors.textPrimary,
                    fontSize: 14,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      content
                          .toString()
                          .replaceAll('-', '')
                          .replaceAll('.0', ''),
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color:
                            content > 0 ? Color(0xFFFD5864) : Color(0xFF53E0B1),
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Image.asset(
                      content > 0
                          ? 'assets/images/cloud/up.png'
                          : 'assets/images/cloud/down.png',
                      width: 20,
                      height: 20,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    ),
  ];
}

class PieChartSample3 extends StatefulWidget {
  final List<dynamic>? prediction;
  const PieChartSample3({super.key, this.prediction});

  @override
  State<StatefulWidget> createState() => PieChart3State();
}

class PieChart3State extends State<PieChartSample3> {
  int touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;

    return AspectRatio(
      aspectRatio: 1.3,
      child: Stack(
        children: <Widget>[
          Positioned(
            left: (screenWidth - 180) / 2,
            top: 80,
            width: 100,
            height: 100,
            child: Center(
              child: AspectRatio(
                aspectRatio: 1,
                child: Stack(
                  children: [
                    PieChart(
                      PieChartData(
                        pieTouchData: PieTouchData(
                          touchCallback:
                              (FlTouchEvent event, pieTouchResponse) {
                            setState(() {
                              if (!event.isInterestedForInteractions ||
                                  pieTouchResponse == null ||
                                  pieTouchResponse.touchedSection == null) {
                                touchedIndex = -1;
                                return;
                              }
                              touchedIndex = pieTouchResponse
                                  .touchedSection!.touchedSectionIndex;
                            });
                          },
                        ),
                        borderData: FlBorderData(
                          show: false,
                        ),
                        sectionsSpace: 5,
                        centerSpaceRadius: 70,
                        sections: showingSections(widget.prediction ?? []),
                      ),
                    ),
                    Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '${_calculateTotalPdi(widget.prediction ?? [])}',
                            style: TextStyle(
                              fontSize: 20,
                              color: AppColors.textPrimary,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            '总数',
                            style: TextStyle(
                              fontSize: 16,
                              color: AppColors.textSecondary,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<PieChartSectionData> showingSections(List<dynamic> data) {
    return List.generate(data.length, (i) {
      final isTouched = i == touchedIndex;
      final fontSize = 10.0;
      final radius = 18.0;
      const shadows = [Shadow(color: Colors.black, blurRadius: 11)];
      final bgcolos = [
        Color(0xFF2AB6F7),
        Color(0xFF814FF3),
        Color(0xFF53E0B1),
        Color(0xFFFCAA3F),
        Color(0xFFFD5864),
      ];
      return PieChartSectionData(
          color: bgcolos[i],
          value: data[i]['ratio'],
          title: data[i]['ratio'].toString() + '%',
          radius: radius,
          titleStyle: TextStyle(
            fontSize: fontSize,
            fontWeight: FontWeight.bold,
            color: AppColors.textSecondary,
          ));
    });
  }
}

class PieChartSample2 extends StatefulWidget {
  const PieChartSample2({super.key, required this.initialv});
  final double initialv;
  @override
  State<PieChartSample2> createState() => PieChart2State();
}

class PieChart2State extends State<PieChartSample2> {
  int touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1,
      child: Stack(
        children: <Widget>[
          Positioned(
            left: 15,
            top: 10,
            width: 180,
            height: 180,
            child: Center(
              child: AspectRatio(
                aspectRatio: 1,
                child: PieChart(
                  PieChartData(
                    pieTouchData: PieTouchData(
                      touchCallback: (FlTouchEvent event, pieTouchResponse) {
                        setState(() {
                          if (!event.isInterestedForInteractions ||
                              pieTouchResponse == null ||
                              pieTouchResponse.touchedSection == null) {
                            touchedIndex = -1;
                            return;
                          }
                          touchedIndex = pieTouchResponse
                              .touchedSection!.touchedSectionIndex;
                        });
                      },
                    ),
                    borderData: FlBorderData(
                      show: false,
                    ),
                    sectionsSpace: 0,
                    centerSpaceRadius: 90,
                    sections: showingSections(widget.initialv),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<PieChartSectionData> showingSections(double values) {
    return List.generate(2, (i) {
      final isTouched = i == touchedIndex;
      final fontSize = isTouched ? 25.0 : 20.0;
      final radius = 10.0;
      const shadows = [Shadow(color: Colors.black, blurRadius: 11)];
      switch (i) {
        case 0:
          return PieChartSectionData(
            color: Color(0xFFF1F1F1),
            value: 40,
            showTitle: false,
            radius: radius,
          );
        case 1:
          return PieChartSectionData(
            gradient: LinearGradient(
              colors: [
                Color.fromARGB(255, 6, 180, 248),
                Color(0xFFF1F1F1),
              ],
              begin: Alignment.topCenter,
              end: Alignment.bottomRight,
            ),
            value: values,
            showTitle: false,
            radius: radius,
          );
        default:
          throw Error();
      }
    });
  }
}

// 计算 totalPdi 的总和
double _calculateTotalPdi(List<dynamic> prediction) {
  return prediction.fold(0, (sum, item) => sum + (item['totalPdi'] ?? 0));
}
